using GroupSix.Application.Dtos;
using GroupSix.Application.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Security.Claims;
using GroupSix.Api.Attributes;

namespace GroupSix.Api.Controllers;

/// <summary>
/// 系统设置控制器
/// </summary>
[ApiController]
[Route("api/[controller]")]
[RequirePermission("systemsetting")]
public class SystemSettingController : ControllerBase
{
    private readonly SystemSettingService _systemSettingService;
    private readonly ILogger<SystemSettingController> _logger;

    public SystemSettingController(SystemSettingService systemSettingService, ILogger<SystemSettingController> logger)
    {
        _systemSettingService = systemSettingService;
        _logger = logger;
    }

    /// <summary>
    /// 获取系统设置列表
    /// </summary>
    /// <param name="query">查询条件</param>
    /// <returns>系统设置列表</returns>
    [HttpGet("list")]
    public async Task<IActionResult> GetSystemSettings([FromQuery] SystemSettingQueryDto query)
    {
        try
        {
            var result = await _systemSettingService.GetSystemSettingsAsync(query);
            return Ok(new { success = true, data = result, message = "获取系统设置列表成功" });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取系统设置列表失败");
            return StatusCode(500, new { success = false, message = "获取系统设置列表失败" });
        }
    }

    /// <summary>
    /// 根据键获取系统设置
    /// </summary>
    /// <param name="settingKey">设置键</param>
    /// <returns>系统设置</returns>
    [HttpGet("key/{settingKey}")]
    public async Task<IActionResult> GetSystemSettingByKey(string settingKey)
    {
        try
        {
            var setting = await _systemSettingService.GetSystemSettingByKeyAsync(settingKey);
            if (setting == null)
            {
                return NotFound(new { success = false, message = "系统设置不存在" });
            }

            return Ok(new { success = true, data = setting, message = "获取系统设置成功" });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "根据键获取系统设置失败: {SettingKey}", settingKey);
            return StatusCode(500, new { success = false, message = "获取系统设置失败" });
        }
    }

    /// <summary>
    /// 根据分组获取系统设置
    /// </summary>
    /// <param name="group">分组</param>
    /// <returns>系统设置列表</returns>
    [HttpGet("group/{group}")]
    public async Task<IActionResult> GetSystemSettingsByGroup(string group)
    {
        try
        {
            var settings = await _systemSettingService.GetSystemSettingsByGroupAsync(group);
            return Ok(new { success = true, data = settings, message = "获取系统设置分组成功" });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "根据分组获取系统设置失败: {Group}", group);
            return StatusCode(500, new { success = false, message = "获取系统设置分组失败" });
        }
    }

    /// <summary>
    /// 创建系统设置
    /// </summary>
    /// <param name="request">创建请求</param>
    /// <returns>创建结果</returns>
    [HttpPost("create")]
    [RequireAdmin]
    public async Task<IActionResult> CreateSystemSetting([FromBody] CreateSystemSettingRequestDto request)
    {
        try
        {
            // 获取当前用户信息
            var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier);
            var userNameClaim = User.FindFirst(ClaimTypes.Name);

            if (userIdClaim == null || userNameClaim == null)
            {
                return Unauthorized(new { success = false, message = "用户未认证" });
            }

            var userId = Guid.Parse(userIdClaim.Value);
            var userName = userNameClaim.Value;

            var result = await _systemSettingService.CreateSystemSettingAsync(request, userId, userName);
            
            if (result)
            {
                return Ok(new { success = true, message = "系统设置创建成功" });
            }
            else
            {
                return BadRequest(new { success = false, message = "系统设置创建失败" });
            }
        }
        catch (InvalidOperationException ex)
        {
            return BadRequest(new { success = false, message = ex.Message });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "创建系统设置失败");
            return StatusCode(500, new { success = false, message = "创建系统设置失败" });
        }
    }

    /// <summary>
    /// 更新系统设置
    /// </summary>
    /// <param name="id">设置ID</param>
    /// <param name="request">更新请求</param>
    /// <returns>更新结果</returns>
    [HttpPut("update/{id}")]
    [RequireAdmin]
    public async Task<IActionResult> UpdateSystemSetting(Guid id, [FromBody] UpdateSystemSettingRequestDto request)
    {
        try
        {
            // 获取当前用户信息
            var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier);
            var userNameClaim = User.FindFirst(ClaimTypes.Name);

            if (userIdClaim == null || userNameClaim == null)
            {
                return Unauthorized(new { success = false, message = "用户未认证" });
            }

            var userId = Guid.Parse(userIdClaim.Value);
            var userName = userNameClaim.Value;

            var result = await _systemSettingService.UpdateSystemSettingAsync(id, request, userId, userName);
            
            if (result)
            {
                return Ok(new { success = true, message = "系统设置更新成功" });
            }
            else
            {
                return BadRequest(new { success = false, message = "系统设置更新失败" });
            }
        }
        catch (InvalidOperationException ex)
        {
            return BadRequest(new { success = false, message = ex.Message });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "更新系统设置失败: {Id}", id);
            return StatusCode(500, new { success = false, message = "更新系统设置失败" });
        }
    }

    /// <summary>
    /// 删除系统设置
    /// </summary>
    /// <param name="id">设置ID</param>
    /// <returns>删除结果</returns>
    [HttpDelete("delete/{id}")]
    [RequireAdmin]
    public async Task<IActionResult> DeleteSystemSetting(Guid id)
    {
        try
        {
            // 获取当前用户信息
            var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier);
            var userNameClaim = User.FindFirst(ClaimTypes.Name);

            if (userIdClaim == null || userNameClaim == null)
            {
                return Unauthorized(new { success = false, message = "用户未认证" });
            }

            var userId = Guid.Parse(userIdClaim.Value);
            var userName = userNameClaim.Value;

            var result = await _systemSettingService.DeleteSystemSettingAsync(id, userId, userName);
            
            if (result)
            {
                return Ok(new { success = true, message = "系统设置删除成功" });
            }
            else
            {
                return BadRequest(new { success = false, message = "系统设置删除失败" });
            }
        }
        catch (InvalidOperationException ex)
        {
            return BadRequest(new { success = false, message = ex.Message });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "删除系统设置失败: {Id}", id);
            return StatusCode(500, new { success = false, message = "删除系统设置失败" });
        }
    }

    /// <summary>
    /// 获取设置变更日志
    /// </summary>
    /// <param name="settingKey">设置键</param>
    /// <param name="page">页码</param>
    /// <param name="pageSize">页大小</param>
    /// <returns>变更日志</returns>
    [HttpGet("logs/{settingKey}")]
    public async Task<IActionResult> GetSettingLogs(string settingKey, [FromQuery] int page = 1, [FromQuery] int pageSize = 20)
    {
        try
        {
            var result = await _systemSettingService.GetSettingLogsAsync(settingKey, page, pageSize);
            return Ok(new { success = true, data = result, message = "获取设置变更日志成功" });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取设置变更日志失败: {SettingKey}", settingKey);
            return StatusCode(500, new { success = false, message = "获取设置变更日志失败" });
        }
    }

    /// <summary>
    /// 获取最近的设置变更日志
    /// </summary>
    /// <param name="page">页码</param>
    /// <param name="pageSize">页大小</param>
    /// <returns>变更日志</returns>
    [HttpGet("logs/recent")]
    public async Task<IActionResult> GetRecentLogs([FromQuery] int page = 1, [FromQuery] int pageSize = 20)
    {
        try
        {
            var result = await _systemSettingService.GetRecentLogsAsync(page, pageSize);
            return Ok(new { success = true, data = result, message = "获取最近设置变更日志成功" });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取最近设置变更日志失败");
            return StatusCode(500, new { success = false, message = "获取最近设置变更日志失败" });
        }
    }
} 